package
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	import flash.utils.Timer;
	
	public class Ocean extends Sprite
	{
		public var loader:URLLoader;
		public var imageLoader:Loader = new Loader();
		public var imageCount:int = 147;
		public var cache:Vector.<ByteArray> = new Vector.<ByteArray>(147);
//		public var backData:BitmapData;
//		public var fontData:BitmapData;
		public var image:Bitmap = new Bitmap();
		public var timer:Timer = new Timer(1000);
		public var index:int = 0;
		public var colors:Array = [ 0xFF56f5d8, 0xFF00ecad, 0xFF75f038,
			0xFFcfff00, 0xFFffff00, 0xFFffea50, 0xFFffcd50, 0xFFffa250,
			0xFFff7f50, 0xFFff6347, 0xFFff0000 ];
		public var scales:Vector.<Sprite> = new Vector.<Sprite>(colors.length);
		public var scaleSlot:Sprite = new Sprite();
		
		public function Ocean()
		{
			var g:Graphics;
			for (var i:int = 0; i < scales.length; i++) {
				scales[i] = new Sprite;
				g = scales[i].graphics;
				g.beginFill(colors[i]);
				g.drawRect(0, 0, 60, 20);
				scales[i].name = i+"";
				scales[i].y = i * 20;
				scales[i].addEventListener(MouseEvent.CLICK, onClickScale);
				scaleSlot.addChild(scales[i]);								
			}
			scaleSlot.x = 300;
			addChild(scaleSlot);
			loader = new URLLoader(new URLRequest("../../../java/BitmapTest/data"));
			loader.dataFormat = URLLoaderDataFormat.BINARY;
			loader.addEventListener(Event.COMPLETE, onLoad);
		}
		
		public function onClickScale(e:MouseEvent):void {
			var s:Sprite = e.currentTarget as Sprite;
			var index:int = int(s.name);
			trace("click index " + index); 
		}
		
		public function onLoad(e:Event):void {
			var data:ByteArray = loader.data as ByteArray;
			data.endian = Endian.LITTLE_ENDIAN;
			var len:int;
			var imageData:ByteArray;
			for (var i:int = 0; i < imageCount; i++) {
				len = data.readInt();
				imageData = new ByteArray();
				data.readBytes(imageData, 0, len);
				cache[i] = imageData;
				trace("cache " + i);
			}
			imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaded);
			addChild(image);
			timer.addEventListener(TimerEvent.TIMER, onTimer);
			timer.start();
			loadNext();
		}
		
		public function loadNext():void {
			imageLoader.loadBytes(cache[index]);
			index = (index+1)%imageCount;
		}
		
		public function onLoaded(e:Event):void {
			image.bitmapData = (imageLoader.content as Bitmap).bitmapData;
		}
		
		public function onTimer(e:Event):void {			
			loadNext();
		}
	}
}